import wxValidate from 'wechat-validate'
const app = getApp()
Page({
  // 引入表单验证
  behaviors: [wxValidate],
  data: {
    countDownVisible: false,
    mobileCode: '',
    mobile: '',
    redirectUrl: '',
    routeType: '',
  },
  rules: {
    // 定义表单验证规则
    mobile: [
      { required: true, message: '请输入手机号!' },
      { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '手机号格式不正确!' },
    ],
  },
  onLoad({ redirectUrl, routeType }) {
    // 获取redirectUrl
    this.setData({
      redirectUrl,
      routeType,
    })
  },
  // 倒计时
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 获取手机验证码
  async getSMSCode() {
    const { valid, message } = this.validate('mobile')
    if (!valid) return wx.utils.messagePrompt(message)
    // 发送验证码逻辑
    this.setData({
      countDownVisible: true,
    })
    await wx.http.get('/code', { mobile: this.data.mobile }).then((res) => {
      if (res.code !== 10000) return wx.utils.messagePrompt('发送失败，请稍后重试！')
      this.setData({
        mobileCode: res.data.code,
      })
    })
  },
  // 提交表单逻辑
  async submitForm() {
    if (!this.validate()) return
    await wx.http
      .post('/login', {
        mobile: this.data.mobile,
        code: this.data.mobileCode,
      })
      .then((res) => {
        if (res.code !== 10000) return wx.utils.messagePrompt('登录失败，请稍后重试！')
        // 登录成功后，将token存储到本地
        app.setToken('token', res.data.token)
        app.setToken('refreshToken', res.data.refreshToken)
        // 跳转到需要登录的页面
        // console.log(this.data.redirectUrl)
        wx[this.data.routeType]({
          url: this.data.redirectUrl,
          success: (res) => {
            console.log('1', res)
          },
          fail: (res) => {
            console.log(this.data.redirectUrl)
            console.log('2', res)
          },
          complete: (res) => {
            console.log('3', res)
          },
        })
        wx.utils.messagePrompt('登录成功！')
      })
  },
})
